package com.yhny.lykj.yuhannongye.app;


import android.app.Fragment;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.longsichao.lscframe.ctrl.DataManager;
import com.longsichao.lscframe.model.LSCModel;
import com.longsichao.lscframe.net.Api;
import com.longsichao.lscframe.view.LSCToast;
import com.yhny.lykj.yuhannongye.MyApplication;
import com.yhny.lykj.yuhannongye.R;
import com.yhny.lykj.yuhannongye.model.BaseModel;
import com.yhny.lykj.yuhannongye.tools.LCLog;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import java.util.LinkedList;
import java.util.List;


/**
 * A simple {@link Fragment} subclass.
 */
public abstract class BaseRefreshListFragment<M> extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener {

    /**
     * Fragment当前状态是否可见
     */
    protected boolean isVisible;
    private TextView tipView;
    private SwipeRefreshLayout refreshLayoutView;
    private RecyclerView.LayoutManager layoutManager;
    private BaseRefreshListAdapter adapter;
    private List<M> dataList = new LinkedList<>();
    private int lastVisibleItem = 0;
    private boolean isLoadMore = true;
    private int currentPage = 1;
    private boolean isFirstLoad = true;
    private RecyclerView recyclerView;

    protected abstract Boolean isGridView();
    protected void preloadData(View view, Bundle savedInstanceState) {
    }

    protected abstract String setTipText();

    protected boolean canLoadMore() {
        return true;
    }

    private void loadData(int page) {
        currentPage = page;
        if (isFirstLoad) {
            isFirstLoad = false;
            showProgressDialog(R.string.text_loading);
        }
        DataManager.getData(MODEL_PROCESS_0, getApi(currentPage), this);
    }

    protected abstract Api getApi(int page);

    protected List<M> getDataList() {
        return dataList;
    }

    protected abstract BaseRefreshListAdapter getRefreshListAdapter();

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
    }

    /**
     * getArguments ��ȡbundle����
     */
    protected void onSetContentViewAfter(View rootView) {
    }    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(getLayoutResId(), container, false);
        tipView = (TextView)rootView.findViewById(R.id.tip);
        if (!TextUtils.isEmpty(setTipText())) {
            tipView.setText(setTipText());
        }
        refreshLayoutView = (SwipeRefreshLayout) rootView.findViewById(R.id.refresh);
        refreshLayoutView.setOnRefreshListener(this);
        refreshLayoutView.setRefreshing(true);
        recyclerView = (RecyclerView) rootView.findViewById(R.id.list);
        onSetContentViewAfter(rootView);
        resetLayoutManagerAndAdapter();
        refreshLayoutView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                isLoadMore = true;
                loadData(1);
            }
        });
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (layoutManager instanceof LinearLayoutManager) {
                    lastVisibleItem = ((LinearLayoutManager) layoutManager).findLastVisibleItemPosition();
                }
            }

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (canLoadMore() && isLoadMore && newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItem + 1 >= adapter.getItemCount()) {
                    loadData(currentPage + 1);
                    LSCToast.show(MyApplication.getContext(), R.string.text_load_more);
                }
            }
        });
        recyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(getContext()).sizeResId(R.dimen.item_vertical_margin).colorResId(R.color.colorDivider).build());

        return rootView;
    }

    protected RecyclerView.LayoutManager getLayoutManager() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        return linearLayoutManager;
    }
    protected RecyclerView.LayoutManager getLayoutManger(int num){
        final LSCGridLayoutManager layoutManager1 = new LSCGridLayoutManager(getContext(),num);
        layoutManager1.setOrientation(LinearLayoutManager.VERTICAL);
        return layoutManager1;
    }
    protected void resetLayoutManagerAndAdapter() {
        if (isGridView()){
            layoutManager = getLayoutManger(2);
        }else{
            layoutManager = getLayoutManager();
        }
        recyclerView.setLayoutManager(layoutManager);
        adapter = getRefreshListAdapter();

        recyclerView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        preloadData(view, savedInstanceState);
        if (isLoadDataInFirst()) {
            loadData(1);
        }
    }


    @Override
    public void onResume() {
        loadData(1);
        super.onResume();
    }

    protected boolean isLoadDataInFirst() {
        return true;
    }

    protected int getLayoutResId() {
        return R.layout.fragment_refresh_list;
    }

    @Override
    public void onRefresh() {
        isLoadMore = true;
        loadData(1);
    }

    protected void refreshDataList() {
        showNoDataMsg(false);
        refreshLayoutView.setRefreshing(true);
        onRefresh();
    }

    protected abstract List<M> getModelDataList(LSCModel model);

    @Override
    public boolean onModel(int caseId, LSCModel model) {
        if (super.onModel(caseId, model)||model==null) {
//            LSCToast.show(getActivity(),"请检查网络！");
            dismissProgressDialog();
            return true;
        }
        switch (caseId) {
            case MODEL_PROCESS_0:

                BaseModel baseModel = (BaseModel)model;
                if (isDataEmpty(baseModel)){
                    if (currentPage == 1) {
                        showNoDataMsg(true);
                        LCLog.e("1");
                    } else {
                        isLoadMore = false;
                        showNoDataMsg(false);
                        LCLog.e("2");
                    }

                }else{
                    List<M> modelDataList = getModelDataList(model);
                    if (modelDataList == null || modelDataList.isEmpty()) {
                        if (currentPage == 1) {
                            showNoDataMsg(true);
                            LCLog.e("3");
                        } else {
                            isLoadMore = false;
                            showNoDataMsg(false);
                            LCLog.e("4");

                        }
                    } else {
                        if (currentPage == 1) {
                            dataList.clear();
                        }
                        LCLog.e("5");

                        dataList.addAll(modelDataList);
                        adapter.notifyDataSetChanged();
                        showNoDataMsg(false);
                    }
                }

                refreshLayoutView.setRefreshing(false);
                dismissProgressDialog();
                return true;
        }
        return false;
    }

    private void showNoDataMsg(boolean isShow) {
        tipView.setVisibility(isShow ? View.VISIBLE : View.GONE);
        refreshLayoutView.setVisibility(isShow ? View.GONE : View.VISIBLE);
    }
}
